<template>
  <div class="login-viwe">
    <van-nav-bar
      title="黑马头条登录"
    />
    <van-form ref="loginForm">
      <van-field
        v-model="reqParams.mobile"
        label="手机号"
        placeholder="请输入用户名"
        :rules="[
          { required: true, message: '请填写手机号', trigger: 'onBlur'},
          { validator: mobileValidator, message: '手机号必须是11位数字', trigger: 'onBlur'}
        ]"
      />
      <van-field
        v-model="reqParams.code"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码', trigger: 'onBlur'}]"
      />
    </van-form>
    <div class="login-btn">
      <van-button @click="totalValidator" class="btn" type="info">登录</van-button>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'Login',
  data () {
    return {
      reqParams: {
        mobile: '13599999999',
        code: '246810'
      }
    }
  },
  methods: {
    // 用户名效验
    mobileValidator (value) {
      // value 就是要验证的内容
      // 返回的是布尔值，验证成功或失败
      return /1\d{10}/.test(value)
    },
    // 发送请求登录
    hLogin () {
      login(this.reqParams).then(res => {
        // 登录成功后，获取到token
        // console.log(res.data.data)
        // 把token设置给 vuex
        this.$store.commit('setToken', res.data.data)
        // console.log(this.$route.query.backto)
        // 获取因为token错误而跳转过来的路径
        const backto = this.$route.query.backto
        if (backto) {
          this.$router.push({ path: backto }) // 哪里来登录之后去哪里
        } else {
          // 登录成功跳转
          this.$router.push('/')
        }
      })
    },
    // 总体效验
    totalValidator () {
      // console.log(this.$refs.loginForm)
      this.$refs.loginForm.validate().then(() => {
        // 验证成功发送请求
        this.hLogin()
      }).catch(() => {
        console.log('验证失败')
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .login-btn {
    padding: 20px;
    .btn {
      width: 100%;
      background-color: #3196fa;
      color: #fff;
    }
  }
</style>
